package org.danger.t7.common.meters.http;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import io.micrometer.core.instrument.MeterRegistry;
import org.danger.t7.common.meters.KeyAndTags;
import org.danger.t7.common.meters.Meters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * PrometheusInterceptor
 * <p>
 * 查询应用的请求总量: sum(http_requests_total)
 * 查询每秒Http请求量: sum(rate(http_requests_total[5m]))
 * 查询当前应用请求量Top N的URI: topk(10, sum(http_requests_total) by (path))
 * <p>
 * https://blog.csdn.net/nandao158/article/details/120326987
 */
@Deprecated
public class WebPrometheusInterceptor implements HandlerInterceptor {

    @Autowired
    private MeterRegistry meter;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        int status = response.getStatus();

        // "path", "method", "code"
        Meters.counter(KeyAndTags.key("http_requests_total")
                .tag("path", requestURI)
                .tag("method", method)
                .tag("code", String.valueOf(status))
        ).increment();

        Meters.gauge(KeyAndTags.key("http_inprogress_requests")
                .tag("path", requestURI)
                .tag("method", method)
                .tag("code", String.valueOf(status)), 0
        ).incrementAndGet();

        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        int status = response.getStatus();
        //当前正在处理的请求数 - 1
        Meters.gauge(KeyAndTags.key("http_inprogress_requests")
                .tag("path", requestURI)
                .tag("method", method)
                .tag("code", String.valueOf(status)), 0
        ).decrementAndGet();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);

    }
}
/*
return Histogram.build().labelNames("path", "method", "code")
        .name("http_requests_bytes_histogram").help("http bucket 请求大小区间分布图")
        .register(collectorRegistry);
 */